package com.xindaoapp.henghua.activity;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.http.Header;
import org.apache.http.message.BasicHeader;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.library.utils.IRequest;
import com.library.utils.KeyValuePair;
import com.library.utils.ThreadPool;
import com.xindaoapp.henghua.R;
import com.xindaoapp.henghua.application.XinDaoApplication;
import com.xindaoapp.henghua.entry.Photos;
import com.xindaoapp.henghua.entry.PropertyGatherInfo;
import com.xindaoapp.henghua.entry.PropertyGatherInfo.MODIFIEDTYPE;
import com.xindaoapp.henghua.entry.PropertyLabelInfo;
import com.xindaoapp.henghua.entry.ScanData;
import com.xindaoapp.henghua.entry.TagsInfo;
import com.xindaoapp.henghua.entry.TransportDataInfo;
import com.xindaoapp.henghua.utils.BitmapUtils;
import com.xindaoapp.henghua.utils.CommFunc;
import com.xindaoapp.henghua.utils.UploadFile;
import com.xindaoapp.henghua.utils.XZip;
import com.xindaoapp.henghua.view.HSVAdapter;
import com.xindaoapp.henghua.view.HSVLayout;
import com.xindaoapp.henghua.zbar.CameraTestActivity;

/**
 * 添加标签
 * @author xyf
 */
public class AddLabel extends BaseActivity implements OnClickListener, OnCheckedChangeListener {

	/**　设备编号*/
	private TextView tv_deviceCode;
	/**　设备名称*/
	private TextView tv_deviceName;
	/**　贴签时间*/
	private TextView tv_signTime;
	/**　监造人*/
	private TextView tv_built_person;
	/**　操作员位置*/
	private TextView tv_location;
	/**　贴签部位*/
	private EditText et_other;
	/**　备注*/
	private EditText et_remark;
	/**　贴签部位 顶部*/
	private CheckBox cb_top;
	/**　贴签部位 中部*/
	private CheckBox cb_middle;
	/**　贴签部位 底部*/
	private CheckBox cb_bottom;
	/**　定位按钮*/
	private ImageButton ib_location;
	/**　拍照按钮*/
	private ImageButton ib_camera;
	/**　提交并返回*/
	private Button btn_submit_back;
	/**　提交并继续*/
	private Button btn_submit_go_ahead;
	/**　照片数量*/
	private TextView tv_photoNums;

	private final List<CheckBox> checkBoxs = new ArrayList<CheckBox>();
	private int checkedIndex = -1;
	private final String[] partArray = { "顶部", "中部", "底部" };

	/** 百度地图获取位置相关*/
	public LocationClient mLocationClient = null;
	// public GeofenceClient mGeofenceClient;
	public MyLocationListenner myListener = new MyLocationListenner();
	/** 位置*/
	private String addrStr = "";
	/** 纬度*/
	private double lat = 0;
	/** 经度*/
	private double lng = 0;

	/** 自定义LinearLayout*/
	private HSVLayout movieLayout = null;
	/** 自定义LinearLayout适配器*/
	private HSVAdapter adapter = null;

	/** 时间*/
	private String timeStr = "";

	String photoName = "";
	String photoThumName = "";
	String newPhotoName = "";

	/** 创建当前设备图片目录*/
	String photpFolder = "";

	/** 创建当前设备缩略图图片目录*/
	String photpThumFolder = "";

	/** 设备编码*/
	String deviceCode = "";

	/** 标签编码*/
	String scanCode = "";

	/** 标签id*/
	String scanId = UUID.randomUUID().toString();

	/** 缩略图集合 */
	public List<String> breviaryphotos = null;
	/** 大图片（原始照片）集合*/
	public List<String> photphotos = null;

	/** 缩略图集合 */
	public List<String> allBreviaryphotos = new ArrayList<String>();
	/** 大图片（原始照片）集合*/
	public List<String> allPhotphotos = new ArrayList<String>();

	/** 保存和当前标签相关的图片的信息,缩略图*/
	private final List<Map<String, String>> breList = new ArrayList<Map<String, String>>();
	/** 保存和当前标签相关的图片的信息*/
	private final List<Map<String, String>> imageList = new ArrayList<Map<String, String>>();

	/** 保存和当前设备相关的图片的信息,缩略图*/
	private final List<Map<String, String>> allBreList = new ArrayList<Map<String, String>>();
	/** 保存和当前设备相关的图片的信息*/
	private final List<Map<String, String>> allImageList = new ArrayList<Map<String, String>>();

	/** 获取设备相关所有信息*/
	private PropertyGatherInfo info = null;

	// private final String[] urls = {
	// "http://f.hiphotos.bdimg.com/album/s%3D680%3Bq%3D90/sign=6b62f61bac6eddc422e7b7f309e0c7c0/6159252dd42a2834510deef55ab5c9ea14cebfa1.jpg",
	// "http://g.hiphotos.bdimg.com/album/s%3D680%3Bq%3D90/sign=e58fb67bc8ea15ce45eee301863b4bce/a5c27d1ed21b0ef4fd6140a0dcc451da80cb3e47.jpg",
	// "http://imgsrc.baidu.com/forum/pic/item/5256531ed21b0ef45aa5ddd8ddc451da80cb3e7f.jpg",
	// "http://imgsrc.baidu.com/forum/pic/item/fcc19d19ebc4b74529d9f290cffc1e178b82157f.jpg",
	// "http://c.hiphotos.bdimg.com/album/s%3D680%3Bq%3D90/sign=cdab1512d000baa1be2c44b3772bc82f/91529822720e0cf3855c96050b46f21fbf09aaa1.jpg"
	// };

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		mLocationClient = new LocationClient(this);
		mLocationClient.setAK("8E0E9569C6A496D46857F2881E036F076F3E37CC");
		mLocationClient.registerLocationListener(myListener);
		// mGeofenceClient = new GeofenceClient(this);

		setContentView(R.layout.activity_add_label);
		initWidget(savedInstanceState);

	}

	@SuppressLint("NewApi")
	private void setData() {

		info = (PropertyGatherInfo) getIntent().getSerializableExtra("info");
		scanCode = getIntent().getStringExtra("scanCode");

		String str = "";
		if (info != null) {

			str = info.code;
			if (!TextUtils.isEmpty(str)) {
				tv_deviceCode.setText(str);
				deviceCode = str;
			}
			str = info.name;
			if (!TextUtils.isEmpty(str)) {
				tv_deviceName.setText(str);
			}
			str = info.supervision_linkman;
			if (!TextUtils.isEmpty(str)) {
				tv_built_person.setText(str);
			}

			if (info.scanDatas != null) {
				List<ScanData> data = info.scanDatas;

				if (data != null) {
					for (int i = 0; i < data.size(); i++) {
						if (!TextUtils.isEmpty(data.get(i).tag_code)) {

							String code = data.get(i).tag_code;

							if (data.get(i).photos != null) {
								if (data.get(i).photos.breviaryphotos != null) {

									if (scanCode.equals(code)) {
										breviaryphotos = data.get(i).photos.breviaryphotos;
										photphotos = data.get(i).photos.photphotos;
									}
									allBreviaryphotos.addAll(data.get(i).photos.breviaryphotos);
									allPhotphotos.addAll(data.get(i).photos.photphotos);
								}
							}

						}

					}
				}
			}

			TransportDataInfo transportDataInfo = info.transportDataInfo;
			if (transportDataInfo != null) {
				str = transportDataInfo.notes;
				if (!TextUtils.isEmpty(str)) {
					et_remark.setText(str);
				}
			}

		}

	}

	private void changePhoneNum() {
		CharSequence text = getString(R.string.photo, allBreList.size());
		tv_photoNums.setText(text);
	}

	private void initWidget(Bundle savedInstanceState) {

		tv_deviceCode = (TextView) findViewById(R.id.tv_device_id);
		tv_deviceName = (TextView) findViewById(R.id.tv_device_name);
		tv_signTime = (TextView) findViewById(R.id.tv_sign_time);
		tv_photoNums = (TextView) findViewById(R.id.tv_photoNums);
		CharSequence text = getString(R.string.photo, 0);
		tv_photoNums.setText(text);

		timeStr = getDate();
		tv_signTime.setText(timeStr);

		tv_built_person = (TextView) findViewById(R.id.tv_built_person);
		tv_location = (TextView) findViewById(R.id.tv_location);
		// tv_location = (TextView) findViewById(R.id.tv_location);

		et_other = (EditText) findViewById(R.id.et_other);
		et_remark = (EditText) findViewById(R.id.et_remark);

		cb_top = (CheckBox) findViewById(R.id.cb_top);
		cb_middle = (CheckBox) findViewById(R.id.cb_middle);
		cb_bottom = (CheckBox) findViewById(R.id.cb_bottom);

		ib_location = (ImageButton) findViewById(R.id.ib_location);
		ib_camera = (ImageButton) findViewById(R.id.ib_camera);

		btn_submit_back = (Button) findViewById(R.id.btn_submit_back);
		btn_submit_go_ahead = (Button) findViewById(R.id.btn_submit_go_ahead);

		checkBoxs.add(cb_top);
		checkBoxs.add(cb_middle);
		checkBoxs.add(cb_bottom);

		et_other.setOnClickListener(this);
		cb_top.setOnCheckedChangeListener(this);
		cb_middle.setOnCheckedChangeListener(this);
		cb_bottom.setOnCheckedChangeListener(this);

		ib_location.setOnClickListener(this);
		ib_camera.setOnClickListener(this);
		btn_submit_back.setOnClickListener(this);
		btn_submit_go_ahead.setOnClickListener(this);

		setData();
		//确保每次扫描标签时，图片信息为空

		if(savedInstanceState==null ){
			BitmapUtils.delete(new File(BitmapUtils.DEFAULT_CACHE_FOLDER + "/" + deviceCode + "/"+scanCode));
		}

		photpFolder = BitmapUtils.DEFAULT_CACHE_FOLDER + "/" + deviceCode + "/" + scanCode + "/raw/";

		photpThumFolder = BitmapUtils.DEFAULT_CACHE_FOLDER + "/" + deviceCode + "/" + scanCode + "/"
				+ "thum/";

		BitmapUtils.createPath(photpFolder);
		BitmapUtils.createPath(photpThumFolder);

		initImageData();

		movieLayout = (HSVLayout) findViewById(R.id.movieLayout);
		adapter = new HSVAdapter(this);

		for (int i = 0; i < allImageList.size(); i++) {
			Map<String, String> map = allImageList.get(i);
			adapter.addObject(map);
		}

		movieLayout.setAdapter(adapter);

		getLocation();

	}

	/**
	 * 初始化当前缩略图，有网络的和本地拍照的
	 */
	private void initImageData() {

		if (breviaryphotos != null) {
			// 网络的
			for (int i = 0; i < breviaryphotos.size(); i++) {

				Map<String, String> map = new HashMap<String, String>();
				map.put("uri", breviaryphotos.get(i));
				imageList.add(map);
				Map<String, String> map2 = new HashMap<String, String>();
				map2.put("uri", photphotos.get(i));
				breList.add(map2);

			}
		}

		if (allBreviaryphotos != null) {
			for (int i = 0; i < allBreviaryphotos.size(); i++) {
				Map<String, String> map = new HashMap<String, String>();
				map.put("uri", allBreviaryphotos.get(i));
				allBreList.add(map);
				Map<String, String> map2 = new HashMap<String, String>();
				map2.put("uri", allPhotphotos.get(i));
				allImageList.add(map2);

			}
		}

		// 本地拍照的
		List<String> photoPath = BitmapUtils.getFiles(photpFolder, ".jpg", true);
		for (int i = 0; i < photoPath.size(); i++) {
			Map<String, String> map = new HashMap<String, String>();
			System.out.println("photpFolder " + i + "=====  " + photoPath.get(i));
			map.put("uri", "file://" + photoPath.get(i));
			imageList.add(map);
			breList.add(map);

			allBreList.add(map);
			allImageList.add(map);
		}

		changePhoneNum();

	}

	/**
	 * 获取当前时间
	 * @return
	 */
	@SuppressLint("SimpleDateFormat")
	private String getDate() {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return format.format(new Date());

	}

	/**
	 * 获取当前位置信息
	 */
	private void getLocation() {

		setLocationOption();
		mLocationClient.start();

		if (mLocationClient != null && mLocationClient.isStarted())
			mLocationClient.requestLocation();

	}

	// 设置相关参数
	private void setLocationOption() {
		LocationClientOption option = new LocationClientOption();
		option.setCoorType("bd09ll"); // 设置坐标类型
		option.setServiceName("com.baidu.location.service_v2.9");
		option.setAddrType("all");
		option.setScanSpan(0);

		option.setPriority(LocationClientOption.NetWorkFirst); // 设置网络优先

		option.setPoiNumber(10);
		option.disableCache(true);
		mLocationClient.setLocOption(option);

	}

	@Override
	String getTabTitle() {
		return scanCode;
	}

	@Override
	protected boolean onShowDownloadButton() {
		return false;
	}

	@Override
	public void onClick(View v) {
		Intent intent;
		switch (v.getId()) {
		case R.id.et_other:
			for (CheckBox checkBox : checkBoxs) {
				checkBox.setChecked(false);
			}
			checkedIndex = -1;
			break;
		// 获取地址
		case R.id.ib_location:
			getLocation();
			break;
		// 拍照
		case R.id.ib_camera:

			newPhotoName = getPhotoName();// 原图
			intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(photpFolder, newPhotoName)));
			startActivityForResult(intent, 0);
			break;
		case R.id.btn_submit_back:

			update(0);
//			finish();
			break;
		case R.id.btn_submit_go_ahead:
			update(1);
//			intent = new Intent(getBaseContext(), CameraTestActivity.class);
//			Bundle mBundle = new Bundle();
//			mBundle.putSerializable("info", info);
//			intent.putExtras(mBundle);
//			startActivity(intent);
//			finish();
			break;
		}

	}

	private void update(final int type) {
		String part = "";
		for (int i = 0; i < checkBoxs.size(); i++) {
			boolean checked = checkBoxs.get(i).isChecked();
			if (checked) {
				checkedIndex = i;
			}
		}

		if (checkedIndex != -1) {
			part = partArray[checkedIndex];
		} else if (!et_other.getText().toString().equals("")) {
			part = et_other.getText().toString();
		} else {
//			Toast.makeText(AddLabel.this, "贴签部位不能为空！", Toast.LENGTH_SHORT).show();
//			return;
		}

		// 保存到数据库
		final PropertyLabelInfo propertyLabelInfo = new PropertyLabelInfo();

		if (!TextUtils.isEmpty(info.id)) {
			propertyLabelInfo.assert_id = info.id;
		} else {
			propertyLabelInfo.assert_id = "";
		}

		propertyLabelInfo.create_time = timeStr;
		propertyLabelInfo.id = scanId;
		propertyLabelInfo.part = part;
		propertyLabelInfo.tag_code = scanCode;
		propertyLabelInfo.isModified = MODIFIEDTYPE.MODIFIED.ordinal();

		final ScanData scanData = new ScanData();

		if (!TextUtils.isEmpty(info.id)) {
			scanData.assert_id = info.id;
		} else {
			scanData.assert_id = "";
		}
		scanData.id = scanId;
		scanData.isModified = MODIFIEDTYPE.MODIFIED.ordinal();

//		scanData.scan_device = info.code;
		scanData.scan_device = XinDaoApplication.get().getUserInfo().scan_device;
		scanData.scan_devicename = XinDaoApplication.get().getUserInfo().scan_devicename;
		scanData.scan_location = addrStr;
		scanData.scan_location_gps = "(" + lat + "," + lng + ")";
		scanData.scan_time = timeStr;
		scanData.status = "监造";
		scanData.tag_code = scanCode;
		scanData.notes = et_remark.getText().toString();
		scanData.scan_userid = XinDaoApplication.get().getUserInfo().userid;
		scanData.scan_username = XinDaoApplication.get().getUserInfo().username;

		Photos photos = new Photos();
		List<String> ps = new ArrayList<String>();
		for (int i = 0; i < imageList.size(); i++) {
			ps.add(imageList.get(i).get("uri"));
		}
		List<String> brs = new ArrayList<String>();
		for (int i = 0; i < breList.size(); i++) {
			brs.add(breList.get(i).get("uri"));
		}

		photos.photphotos = ps;
		photos.breviaryphotos = brs;

		scanData.photos = photos;

		String json = UploadFile.getJson(propertyLabelInfo, scanData);

		String rawZipFolder = "", thumbZipFolder = "";

		if (scanData.photos.breviaryphotos.size() > 0) {
			rawZipFolder = BitmapUtils.DEFAULT_CACHE_FOLDER + "/" + deviceCode + "/" + scanCode + "/raw.Zip";
			thumbZipFolder = BitmapUtils.DEFAULT_CACHE_FOLDER + "/" + deviceCode + "/" + scanCode
					+ "/thumb.Zip";
		}

		final String tempRawZipFolder = rawZipFolder;
		final String tempThumbZipFolder = thumbZipFolder;

		btn_submit_back.setEnabled(false);
		btn_submit_go_ahead.setEnabled(false);
		
		// 将新拍的照片进入文件压缩

		try {
			XZip.ZipFolder(photpFolder, rawZipFolder, photos.photphotos);
			XZip.ZipFolder(photpThumFolder, thumbZipFolder, photos.breviaryphotos);
		} catch (Exception e) {
			e.printStackTrace();
		}

//		try {
//			XZip.ZipFolder(photpFolder, rawZipFolder);
//			XZip.ZipFolder(photpThumFolder, thumbZipFolder);
//		} catch (Exception e) {
//			e.printStackTrace();
//		}

		/*try {

			List<String> rawPhoto = BitmapUtils.getFiles(photpFolder, ".jpg", true);
			List<String> thumbPhoto = BitmapUtils.getFiles(photpThumFolder, ".jpg", true);

			for (int i = 0; i < rawPhoto.size(); i++) {
				XZip.ZipFolder(thumbPhoto.get(i), thumbZipFolder);
				XZip.ZipFolder(rawPhoto.get(i), rawZipFolder);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}*/

		List<KeyValuePair<String, File>> list = new ArrayList<KeyValuePair<String, File>>();
		list.add(new KeyValuePair<String, File>("breviaryphotos", new File(rawZipFolder)));
		list.add(new KeyValuePair<String, File>("photos", new File(thumbZipFolder)));

		Header[] headers = new Header[1];

		Header header = new BasicHeader("content_json", json);
		headers[0] = header;
		//

		// 将当前已经扫描的标签保存到标签库数据表
		TagsInfo tagsInfo = new TagsInfo();
		tagsInfo.code = scanCode;
		tagsInfo.notes = "";

		XinDaoApplication.get().getDBHelper().insertTags(tagsInfo);

		XinDaoApplication.get().getDBHelper().insertUnSubmitLabel(propertyLabelInfo, scanData);

		/*XinDaoApplication.get().getUpdateDataChanged().addPropertyLabelInfo(propertyLabelInfo);
		XinDaoApplication.get().getUpdateDataChanged().addScanData(scanData);
		// 刷新列表
		XinDaoApplication.get().getUpdateDataChanged().notifyDataChanged();*/

		XinDaoApplication.get().getUpdateDataChanged().refurshDataChanged();

		showDialog(DIALOG_SUBMIT);
		UploadFile.uploadFile(list, headers, new IRequest<Boolean>() {

			@SuppressWarnings("deprecation")
			@Override
			public void request(Boolean t) {
				PropertyLabelInfo propertyLabelInfo = XinDaoApplication.get().getUpdateDataChanged()
						.getPropertyLabelInfo(info.id, scanCode);

				ScanData scanData = XinDaoApplication.get().getUpdateDataChanged()
						.getScanData(info.id, scanCode);
				
				if (t) {
					// 更新数据库中的状态
					XinDaoApplication.get().getDBHelper().resetLabelState(scanData.tag_code);
//					propertyLabelInfo.isModified = MODIFIEDTYPE.UNMODIFIED.ordinal();
//					scanData.isModified = MODIFIEDTYPE.UNMODIFIED.ordinal();
					// 更改缓存中的状态
					XinDaoApplication.get().getUpdateDataChanged().refurshDataChanged();
					// 重新读取数据库中的数据

					removeDialog(DIALOG_SUBMIT);
					Toast.makeText(AddLabel.this, "提交成功", Toast.LENGTH_SHORT).show();
					if (type == 1) {
						Intent intent = new Intent(getBaseContext(), CameraTestActivity.class);
						Bundle mBundle = new Bundle();
						mBundle.putSerializable("info", info);
						intent.putExtras(mBundle);
						startActivity(intent);
						finish();
					}// 刷新列表
					XinDaoApplication.get().getUpdateDataChanged().notifyDataChanged();
					XinDaoApplication.getHandler().post(new Runnable() {

						@Override
						public void run() {
							AddLabel.this.finish();
						}
					});

				} else {
					// 更新数据表中zip包的路径
					XinDaoApplication.get().getDBHelper()
							.updateLabelPhotoFilePath(scanCode, tempRawZipFolder, tempThumbZipFolder);
					propertyLabelInfo.isModified = MODIFIEDTYPE.MODIFIED.ordinal();
					scanData.isModified = MODIFIEDTYPE.MODIFIED.ordinal();

					removeDialog(DIALOG_SUBMIT);
					Toast.makeText(AddLabel.this, "提交失败，请检查网络！！", Toast.LENGTH_SHORT).show();
					if (type == 1) {
						Intent intent = new Intent(getBaseContext(), CameraTestActivity.class);
						Bundle mBundle = new Bundle();
						mBundle.putSerializable("info", info);
						intent.putExtras(mBundle);
						startActivity(intent);
					}// 刷新列表
					XinDaoApplication.get().getUpdateDataChanged().notifyDataChanged();
					XinDaoApplication.getHandler().post(new Runnable() {

						@Override
						public void run() {
							finish();
						}
					});
				}

			}
		}, XinDaoApplication.packageName, XinDaoApplication.versionName);
	}

	private String getPhotoName() {
		String uuid = UUID.randomUUID().toString();
		photoThumName = "thum_" + uuid + ".jpg";
		return "law_" + uuid + ".jpg";
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		// 拍照
		if (requestCode == 0 && resultCode == Activity.RESULT_OK) {

			photoName = newPhotoName;
			Bitmap b = BitmapUtils.getSmallBitmap(photpFolder + photoName);
			ThreadPool.addRunnable(new Runnable() {

				@Override
				public void run() {
					Bitmap thumB = BitmapUtils.getimage(photpFolder + photoName);
					saveBitmap(thumB, photoThumName);
				}
			});

			if (b != null) {

				Map<String, String> map = new HashMap<String, String>();
				map.put("uri", "file://" + photpFolder + photoName);
				adapter.addObject(map);

				imageList.add(map);
				breList.add(map);

				allBreList.add(map);
				allImageList.add(map);

				movieLayout.setAdapter(adapter);

				changePhoneNum();
				 if(!b.isRecycled()){
			         b.recycle();
			         b=null;
			         System.gc();
				 }

			}

		}

	}

	/** 保存方法 */
	public void saveBitmap(Bitmap b, String picName) {
		File f = new File(photpThumFolder, picName);
		if (f.exists()) {
			f.delete();
		}
		try {
			FileOutputStream out = new FileOutputStream(f);
			if(b != null){
				b.compress(Bitmap.CompressFormat.JPEG, 90, out);
			}
			out.flush();
			out.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		switch (buttonView.getId()) {
		case R.id.cb_top:
			if (isChecked) {
				cb_top.setChecked(true);
				cb_middle.setChecked(false);
				cb_bottom.setChecked(false);
				et_other.setText("");
				checkedIndex = 0;
			}

			break;
		case R.id.cb_middle:
			if (isChecked) {
				cb_middle.setChecked(true);
				cb_top.setChecked(false);
				cb_bottom.setChecked(false);
				et_other.setText("");
				checkedIndex = 1;
			}

			break;
		case R.id.cb_bottom:
			if (isChecked) {
				cb_bottom.setChecked(true);
				cb_top.setChecked(false);
				cb_middle.setChecked(false);
				et_other.setText("");
				checkedIndex = 2;
			}

			break;

		}
	}

	/**
	 * 监听函数，有更新位置的时候，格式化成字符串，输出到屏幕中
	 */
	public class MyLocationListenner implements BDLocationListener {
		@Override
		public void onReceiveLocation(BDLocation location) {
			if (location == null)
				return;

			StringBuffer sb = new StringBuffer(256);
			sb.append("time : ");
			sb.append(location.getTime());
			sb.append("\nerror code : ");
			sb.append(location.getLocType());
			sb.append("\nlatitude : ");
			sb.append(location.getLatitude());
			sb.append("\nlontitude : ");
			sb.append(location.getLongitude());
			sb.append("\nradius : ");
			sb.append(location.getRadius());
			if (location.getLocType() == BDLocation.TypeGpsLocation) {
				sb.append("\nspeed : ");
				sb.append(location.getSpeed());
				sb.append("\nsatellite : ");
				sb.append(location.getSatelliteNumber());
			} else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {
				/**
				 * 格式化显示地址信息
				 */
				sb.append("\n省：");
				sb.append(location.getProvince());
				sb.append("\n市：");
				sb.append(location.getCity());
				sb.append("\n区/县：");
				sb.append(location.getDistrict());
				sb.append("\naddr : ");
				sb.append(location.getAddrStr());

				addrStr = location.getAddrStr();

			}

			sb.append("\nsdk version : ");
			sb.append(mLocationClient.getVersion());
			sb.append("\nisCellChangeFlag : ");
			sb.append(location.isCellChangeFlag());

			lat = location.getLatitude();
			lng = location.getLongitude();

			tv_location.setText(addrStr);

		}

		@Override
		public void onReceivePoi(BDLocation poiLocation) {

		}
	}
	
	@Override
	public void onDestroy() {
		mLocationClient.unRegisterLocationListener(myListener);
		super.onDestroy();
	}
    @Override
    protected void onSaveInstanceState(Bundle outState) {
    	 outState.putInt("currentstate", 100);  
    	super.onSaveInstanceState(outState);
    }

}
